﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using LinFu.IoC.Configuration;
using LinFu.IoC.Interfaces;
using LinFu.IoC;
using LinFu.Reflection;

namespace CoreEx.Database.Linq.Implementation
{        
    public class Table<T> : ITable<T>, IInitialize
    {

        private IList<Expression> _loadExpressions = new List<Expression>();
        
        private string _connectionName;
        
        public Table(string connectionName)
        {
            Expression = Expression.Constant(this);
            _connectionName = connectionName;
        }

        public Table(string connnectionName, Expression expression, IQueryProvider provider)
        {
            _connectionName = connnectionName;
            Expression = expression;
            Provider = provider;
        }



        public IEnumerator<T> GetEnumerator()
        {
            return (Provider.Execute<IEnumerable<T>>(Expression)).GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return (Provider.Execute<IEnumerable>(Expression)).GetEnumerator();
        }

        public Expression Expression { get; private set;}
        

        public Type ElementType
        {
            get { return typeof (T); }
        }

        public IQueryProvider Provider { get; private set;}

        public void Initialize(IServiceContainer source)
        {
            if (Provider == null)
                Provider = source.GetService<IQueryProvider>(_connectionName);
        }

        IList<Expression> ILoadOptions.Expressions
        {
            get
            {
                return _loadExpressions;
            }
        }
        
        public void LoadWith<TTarget>(Expression<Func<TTarget, object>> expression)
        {
       
                        
            _loadExpressions.Add(expression);
        }
    }
}
